const superagent = require('superagent');
const cheerio = require('cheerio');
const baseUrl = 'https://wh.ke.com/';
const type = 'ershoufang'
//const select = 'p3'
const select = 'mw1y2lc2f2a2l2p3p2'
const area = [{
        name: '江岸区',
        py: 'jiangan'
    },
    {
        name: '江汉区',
        py: 'jianhan'
    },
    {
        name: '硚口区',
        py: 'qiaokou'
    },
    {
        name: '东西湖区',
        py: 'dongxihu'
    },
    {
        name: '武昌区',
        py: 'wuchang'
    },
    {
        name: '青山区',
        py: 'qingshan'
    },
    {
        name: '洪山区',
        py: 'hongshan'
    },
    {
        name: '黄陂区',
        py: 'huangpi'
    },
    {
        name: '汉阳区',
        py: 'hanyang'
    },
    {
        name: '江夏区',
        py: 'jiangxia'
    },
];
class getBkHouseInfo {
    constructor(baseUrl, data, type, select) {
        this.type = type,
            this.baseUrl = baseUrl,
            this.select = select,
            this.data = data,
            this.result=[]
            // this.fn = function (data) {
            //     this.result.push(data)
            // }
    }
    getHouseHtml(baseUrl, area, type, select, callback) {
        let url = `${baseUrl}${type}/${area}/${select}`;
        superagent.get(url).end(async (errp, resp) => {
            if (errp) {
                throw new Error('获取信息失败');
            } else {
                let b = await this.getHouseInfo(resp);
                callback(b);
            }
        })

    }
    getHouseInfo(data) {
        let houseInfo = [];
        // 访问成功，请求http://news.baidu.com/页面所返回的数据会包含在res.text中。
        let $ = cheerio.load(data.text);
        //return $;
        //找到目标数据所在的页面元素，获取数据
        $('.sellListContent .clear').each((idx, ele) => {
            let house = {
                title: $(ele).find('.img').attr('title'), // 获取新闻标题
                href: $(ele).find('.img').attr('href'),
                info: $(ele).find('.info .title .maidian-detail').attr('title')
            };
            houseInfo.push(house) // 存入最终结果数组
        });
        //console.log(houseInfo);
        return houseInfo
    }
    getTotalInfo() {
        let result=[];
        if (this.data instanceof Array) {
            let fn = function (data) {
          //      console.log('获取数据完成');
          //      console.log('data',data);
                result.push(data);
            };
            for (let i = 0; i < this.data.length; i++) {
                let a = this.getHouseHtml(this.baseUrl, this.data[i].py, this.type, this.select, fn);
            } 
         //  console.log('result',result); 
           
        } else {
            throw new Error('data must be an Array!')
        }
    }
    getResult(){
        return this.result;
    }
}

//module.exports = new getBkHouseInfo(baseUrl, area, type, select);
// let info = new getBkHouseInfo(baseUrl, area, type, select);;
// let all = info.getTotalInfo();
// let alw=info.getResult()
// console.log('a11',all);
// console.log('res',alw);